﻿<template>
    <div class="esChannelOrder-container">
        <el-card shadow="hover">
            <el-form :model="state.queryParams" ref="queryForm" :inline="true">
                <el-form-item :label-width='70' label="渠道名称">
                    <el-select :clearable='true' class='ml10' v-model="state.queryParams.channelId" placeholder="请选择"
                               filterable>
                        <el-option v-for='item in state.channelDict' :key='item.value' :label='item.label'
                                   :value='item.value'/>
                    </el-select>
                </el-form-item>
                <el-form-item :label-width='70' label='省份'>
                    <el-select :clearable='true' class='ml10' v-model='state.queryParams.province' placeholder='请选择'
                               filterable>
                        <el-option v-for='item in optionDict.provinceDict' :key='item.value' :label='item.label'
                                   :value='item.value'/>
                    </el-select>
                </el-form-item>
                <el-form-item :label-width='70' label="产品名称" prop="productName">
                    <el-input class='ml10' placeholder="产品名称" clearable @keyup.enter="handleQuery"
                              v-model="state.queryParams.productName"/>
                </el-form-item>
                <el-form-item :label-width='70' label="手机号码" prop="phone">
                    <el-input placeholder="手机号码" clearable class='ml10' @keyup.enter="handleQuery"
                              v-model="state.queryParams.phone"/>
                </el-form-item>
                <el-form-item :label-width='70' label='订单状态'>
                    <el-select @clear="orderStatusHandleClear" :clearable='true' class='ml10'
                               v-model='state.queryParams.orderStatus' placeholder='请选择'>
                        <el-option v-for='item in optionDict.orderStatusDict' :key='item.value' :label='item.label'
                                   :value='item.value'/>
                    </el-select>
                </el-form-item>
                <el-form-item :label-width='70' label='日期'>
                    <el-date-picker class='ml10' v-model='state.queryParams.dateRange' type='daterange'
                                    inputmode="none"
                                    :shortcuts="selectShortcuts"
                                    placeholder='日期'
                                    date-format="YYYY/MM/DD" value-format="YYYY-MM-DD"
                                    :disabled-date="disableFutureDates"
                                    range-separator='至' start-placeholder='开始日期' end-placeholder='结束日期'
                                    :picker-options="{firstDayOfWeek: 1 }"
                                    :clearable="false"
                    />
                </el-form-item>
                <el-form-item>
                    <el-button-group>
                        <el-button type="primary" icon="ele-Search" @click="handleQuery" :loading="state.loading"
                                   v-auth="'esChannelOrder:query'" > 查询
                        </el-button>
                        <el-button icon="ele-Refresh" @click="resetQuery" v-auth="'esChannelOrder:query'"> 重置
                        </el-button>
                    </el-button-group>
                    <el-button type="success" plain icon="ele-FolderOpened" @click="exportExcel" :loading="state.loading"> 导出</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <el-card shadow="hover" style="margin-top: 8px">
            <div style="margin: -18px 0 20px 0;">
                <el-pagination @size-change="onHandleSizeChange" @current-change="onHandleCurrentChange" class="mt15"
                               :page-sizes="[20, 50, 100]" v-model:current-page="state.queryParams.pageNum" background
                               v-model:page-size="state.queryParams.pageSize"
                               layout="total, sizes, prev, pager, next, jumper"
                               :total="state.total"/>
            </div>
            <el-table :data="state.data" style="width: 100%" v-loading="state.loading" tooltip-effect="light"
                      row-key="id" border stripe highlight-current-row @cell-mouse-enter="TransferIn"
                      @cell-mouse-leave="mark">
                <el-table-column header-align="center" prop="merchantName" label="商户名称" width="100"
                                 show-overflow-tooltip/>
                <el-table-column header-align="center" prop="channelName" label="渠道名称" width="100"
                                 show-overflow-tooltip/>
                <el-table-column header-align="center" prop="productName" label="产品名称" min-width="420"
                                 show-overflow-tooltip/>
                <el-table-column header-align="center" prop="phoneC" label="手机号码" align="center" width="115"
                                 show-overflow-tooltip/>
                <el-table-column header-align="center" prop="province" width="82" label="省份" align="center"
                                 show-overflow-tooltip/>
                <el-table-column header-align="center" prop="city" width="82" label="城市" align="center"
                                 show-overflow-tooltip/>
                <el-table-column header-align="center" prop="informationFee" label="信息费(元)" align="right"
                                 width="100" show-overflow-tooltip>
                    <template #default="scope">
                        {{ (scope.row.informationFee / 1.00).toFixed(2) }}
                    </template>
                </el-table-column>
                <el-table-column header-align="center" prop="channelSettlementPrice" label="渠道结算价格(元)"
                                 align="right" width="150" show-overflow-tooltip>
                    <template #default="scope">
                        {{ (scope.row.channelSettlementPrice / 1.00).toFixed(2) }}
                    </template>
                </el-table-column>
                <el-table-column header-align='center' label="状态" align="center" show-overflow-tooltip width="82">
                    <template #default="scope">
                        <el-tag type="success" v-if="scope.row.orderStatus === 1">成功</el-tag>
                        <el-tag type="warning" v-else-if="scope.row.orderStatus === 2">处理中</el-tag>
                        <el-tag type="danger" v-else-if="scope.row.orderStatus === 3">失败</el-tag>
                        <el-tag type="warning" v-else-if="scope.row.orderStatus === 4">退订</el-tag>
                        <el-tag type="warning" v-else>未知</el-tag>
                    </template>
                </el-table-column>
                <el-table-column header-align="center" prop="orderMessage" label="订单描述" min-width="100"
                                 show-overflow-tooltip/>
                <el-table-column header-align="center" prop="createTime" label="订单时间" min-width="160"
                                 show-overflow-tooltip/>
                <el-table-column header-align="center" prop="syncStatus" label="同步状态" min-width="100" align="center"
                                 show-overflow-tooltip>
                    <template #default="scope">
                        <el-tag type="success" v-if="scope.row.syncStatus === 0">等待</el-tag>
                        <el-tag type="success" v-else-if="scope.row.syncStatus === 1">已完成</el-tag>
                        <el-tag type="success" v-else-if="scope.row.syncStatus === 2">不同步</el-tag>
                        <el-tag type="danger" v-else-if="scope.row.syncStatus === 3">失败</el-tag>
                    </template>
                </el-table-column>
                <el-table-column header-align="center" prop="syncResponse" label="同步结果" min-width="100"
                                 show-overflow-tooltip/>
                <el-table-column header-align="center" prop="syncTime" label="同步时间" min-width="160"
                                 show-overflow-tooltip/>
                <el-table-column header-align="center" prop="merchantOrderId" label="商户订单ID" width="220"
                                 show-overflow-tooltip/>
                <el-table-column header-align="center" prop="extData" label="透传数据" width="100"
                                 show-overflow-tooltip/>
                <el-table-column header-align="center" prop="outOrderId" label="外部订单ID" width="100"
                                 show-overflow-tooltip/>
                <el-table-column header-align="center" prop="productChannelCode" width="80" label="Key"
                                 align="center"
                                 show-overflow-tooltip/>
                <el-table-column header-align="center" prop="productCategoryCode" width="80" label="大Key"
                                 align="center"
                                 show-overflow-tooltip/>
                <el-table-column label="操作" width="60" align="center" fixed="right" show-overflow-tooltip>
                    <template #default="scope">
                        <el-button size="small" text type="primary" @click="openEditEsChannelOrder(scope.row)"
                                   v-auth="'esChannelOrder:detail'">详情
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination @size-change="onHandleSizeChange" @current-change="onHandleCurrentChange" class="mt15"
                           :page-sizes="[20, 50, 100]" v-model:current-page="state.queryParams.pageNum" background
                           v-model:page-size="state.queryParams.pageSize"
                           layout="total, sizes, prev, pager, next, jumper"
                           :total="state.total"/>
            <EditEsChannelOrder ref="editEsChannelOrderRef" :title="state.editTitle"/>
        </el-card>
    </div>
</template>

<script lang="ts" setup name="esChannelOrder">

import {onMounted, onUnmounted, reactive, ref} from 'vue';
import {ElMessage} from 'element-plus';
import {selectShortcuts, disableFutureDates, todayDate} from '/@/utils/dateHelper';
import mittBus from '/@/utils/mitt';
import EditEsChannelOrder from '/@/views/exocytosis/order/channelOrder/component/editEsChannelOrder.vue';
import {EsChannelOrder, sysBaseDict} from '/@/api/models';
import SysEsChannelOrderApi from '/@/api/exocytosis/channelOrder';
import {optionDict} from '/@/const/dict.ts';
import SysEsChannelApi from '/@/api/exocytosis/channel';
import {downloadByData, getFileName} from "/@/utils/download";

// 定义变量内容
const editEsChannelOrderRef = ref<InstanceType<typeof EditEsChannelOrder>>();

const state = reactive({
    loading: false,
    data: [] as Array<EsChannelOrder>,
    total: 0 as any,
    queryParams: {
        channelId: undefined,
        channelName: undefined,
        phone: undefined,
        productName: undefined,
        pageNum: 1,
        pageSize: 20,
        dateRange: [todayDate(), todayDate()],
        orderStatus: undefined,
        province: undefined,
    },
    editTitle: '',
    channelDict: [] as sysBaseDict[],
});

onMounted(async () => {
    await channelDictQuery();
    mittBus.on('submitRefresh', () => {
        handleQuery();
    });
});

onUnmounted(() => {
    mittBus.off('submitRefresh');
});

// 查询操作
const handleQuery = async () => {
    // 1. 验证日期范围
    if (state.queryParams.dateRange.length === 0) {
        return ElMessage.warning('请先选择日期');
    }

    try {
        state.loading = true;

        // 2. 参数处理（自动过滤空值）
        const params = {
            ...state.queryParams,
            // operatorPlatform: state.queryParams.operatorPlatform || undefined // 自动转换空字符串
        };

        // 3. API请求
        const {data} = await SysEsChannelOrderApi().queryRecord(params);

        // 4. 响应处理（安全取值）
        state.data = data?.result?.items || [];
        state.total = data?.result?.total || 0;

        // 手机号脱敏
        const reg = /^(\d{3})\d{4}(\d{4})$/;
        state.data.forEach((item) => {
            item.phoneC = item.phone?.replace(reg, `$1${'*'.repeat(4)}$2`);
        })
    } catch (error) {
        ElMessage.error('数据加载失败');
    } finally {
        state.loading = false;
    }
};

// 重置操作
const resetQuery = () => {
    // 1. 批量重置为undefined
    const keepKeys: string[] = ['pageNum', 'pageSize', 'dateRange']; // 声明需要保留的字段
    Object.keys(state.queryParams).forEach(key => {
        if (!keepKeys.includes(key))
            state.queryParams[key] = undefined;
    });
    // 2. 单独处理日期
    state.queryParams.dateRange = [todayDate(), todayDate()];
    state.data = [];
};

// 打开编辑页面
const openEditEsChannelOrder = (row: EsChannelOrder) => {
    state.editTitle = '详情';
    editEsChannelOrderRef.value?.openDialog(row);
};

// 改变页面容量
const onHandleSizeChange = (val: number) => {
    state.queryParams.pageSize = val;
    handleQuery();
};

// 改变页码序号
const onHandleCurrentChange = (val: number) => {
    state.queryParams.pageNum = val;
    handleQuery();
};

// 渠道列表
const channelDictQuery = async () => {
    await SysEsChannelApi().queryAll().then((res) => {
        if (res.data.resCode === '0000')
            state.channelDict = res.data.result ?? [];
    });
};


// 订单状态清空
const orderStatusHandleClear = () => {
    state.queryParams.orderStatus = undefined
};

const exportExcel = async () => {
    state.loading = true;
    if (state.queryParams.channelId != undefined && state.queryParams.channelId != "")
        state.channelDict.forEach(item => {
            if (item.value == state.queryParams.channelId)
                state.queryParams.channelName = item.label;
        });
    else
        state.queryParams.channelName = undefined;

    SysEsChannelOrderApi().exportExcel(state.queryParams).then((res) => {
        const fileName = getFileName(res.headers);
        downloadByData(res.data as any, fileName);
        state.loading = false;
    });
};

// 鼠标划入电话单元格时
const TransferIn = (row, column, cell, event) => {
    if (column.property == 'phoneC') {
        row.phoneC = row.phone;
        // console.log(row, column, cell, event);
    }
};

// 鼠标移出电话单元格时
const mark = (row, column, cell, event) => {
    if (column.property == 'phoneC') {
        const reg = /^(\d{3})\d{4}(\d{4})$/;
        row.phoneC = row.phoneC.replace(reg, `$1${'*'.repeat(4)}$2`);
    }
};

</script>
